import os
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from image_processor import ImageProcessor
from video_processor import VideoProcessor
from image_stats import MediaStats
import threading
import queue

class MediaOrganizerGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("媒体文件整理工具")
        self.root.geometry("800x600")
        
        # 创建消息队列用于线程间通信
        self.message_queue = queue.Queue()
        
        self.setup_ui()
        self.check_message_queue()
    
    def setup_ui(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 目录选择部分
        select_frame = ttk.LabelFrame(main_frame, text="选择目录", padding="5")
        select_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        ttk.Label(select_frame, text="选择要整理的目录:").grid(row=0, column=0, sticky=tk.W, padx=5)
        
        self.dir_var = tk.StringVar()
        dir_entry = ttk.Entry(select_frame, textvariable=self.dir_var, width=60)
        dir_entry.grid(row=0, column=1, padx=5)
        
        browse_btn = ttk.Button(select_frame, text="浏览", command=self.browse_directory)
        browse_btn.grid(row=0, column=2, padx=5)
        
        # 开始按钮
        start_btn = ttk.Button(select_frame, text="开始整理", command=self.start_processing)
        start_btn.grid(row=1, column=0, columnspan=3, pady=10)
        
        # 进度显示
        self.progress_var = tk.StringVar(value="就绪")
        ttk.Label(select_frame, textvariable=self.progress_var).grid(row=2, column=0, columnspan=3)
        
        # 创建左右分栏
        left_frame = ttk.Frame(main_frame)
        left_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 5))
        
        right_frame = ttk.Frame(main_frame)
        right_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 日志显示区域（左侧）
        log_frame = ttk.LabelFrame(left_frame, text="处理日志", padding="5")
        log_frame.pack(fill=tk.BOTH, expand=True)
        
        self.log_text = tk.Text(log_frame, height=20, width=50)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.configure(yscrollcommand=scrollbar.set)
        
        # 功能介绍（右侧）
        intro_frame = ttk.LabelFrame(right_frame, text="功能介绍", padding="5")
        intro_frame.pack(fill=tk.BOTH, expand=True)
        
        intro_text = """功能说明：

1. 文件重命名
   • 图片：IMG_YYYYMMDD_HHMMSS.ext
   • 视频：VID_YYYYMMDD_HHMMSS.ext
   • 优先使用EXIF拍摄时间
   • 无EXIF则使用修改时间

2. 文件整理
   • 按拍摄日期分类到年/月/日目录
   • 无EXIF信息图片移至web目录
   • 重复文件保留一个，其余移至temp

3. 支持的格式
   • 图片：jpg, jpeg, tiff, nef, cr2, 
         png, bmp
   • 视频：mp4, avi, mov, wmv, flv, 
         mkv

4. 统计功能
   • 文件总数和格式统计
   • 目录文件数量统计
   • 重复文件检测和显示
"""
        intro_label = ttk.Label(intro_frame, text=intro_text, justify=tk.LEFT)
        intro_label.pack(padx=5, pady=5)
        
        # 配置grid的权重
        main_frame.columnconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(1, weight=1)
        
        # 配置root的权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
    
    def browse_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.dir_var.set(directory)
    
    def start_processing(self):
        directory = self.dir_var.get()
        if not directory:
            messagebox.showerror("错误", "请选择要处理的目录！")
            return
        
        if not os.path.exists(directory):
            messagebox.showerror("错误", "所选目录不存在！")
            return
        
        # 禁用开始按钮
        for widget in self.root.winfo_children():
            if isinstance(widget, ttk.Button):
                widget.configure(state='disabled')
        
        # 清空日志
        self.log_text.delete(1.0, tk.END)
        self.progress_var.set("正在处理...")
        
        # 在新线程中处理文件
        thread = threading.Thread(target=self.process_files, args=(directory,))
        thread.daemon = True
        thread.start()
    
    def process_files(self, directory):
        try:
            # 支持的媒体格式
            image_extensions = ('.jpg', '.jpeg', '.tiff', '.nef', '.cr2', '.png', '.bmp')
            video_extensions = ('.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv')
            
            # 创建统计对象
            stats = MediaStats(directory)
            
            # 第一次遍历：重命名所有文件
            self.log_message("\n=== 开始重命名文件 ===")
            for root, dirs, files in os.walk(directory):
                for file in files:
                    try:
                        file_lower = file.lower()
                        file_path = os.path.join(root, file)
                        
                        if file_lower.endswith(image_extensions):
                            processor = ImageProcessor(file_path)
                            processor.rename_file()
                        elif file_lower.endswith(video_extensions):
                            processor = VideoProcessor(file_path)
                            processor.rename_file()
                    except Exception as e:
                        self.log_message(f"重命名文件失败 {file}: {str(e)}")
            
            # 第二次遍历：处理文件并统计
            self.log_message("\n=== 开始处理媒体文件信息 ===")
            for root, dirs, files in os.walk(directory):
                if 'temp' in root:  # 跳过temp目录
                    continue
                    
                self.log_message(f'扫描子目录: {root}')
                for file in files:
                    try:
                        file_lower = file.lower()
                        file_path = os.path.join(root, file)
                        
                        if file_lower.endswith(image_extensions):
                            self.log_message(f'找到图片文件: {file}')
                            processor = ImageProcessor(file_path)
                            processor.process()
                            stats.add_image(file_path)
                        elif file_lower.endswith(video_extensions):
                            self.log_message(f'找到视频文件: {file}')
                            processor = VideoProcessor(file_path)
                            processor.process()
                            stats.add_video(file_path)
                    except Exception as e:
                        self.log_message(f"处理文件失败 {file}: {str(e)}")
            
            # 打印统计信息到日志
            stats_text = stats.print_stats()
            self.log_message(stats_text)
            
            # 整理文件
            stats.organize_files()
            
            self.progress_var.set("处理完成")
            messagebox.showinfo("完成", "文件处理完成！")
            
        except Exception as e:
            self.log_message(f"处理过程出错: {str(e)}")
            self.progress_var.set("处理出错")
            messagebox.showerror("错误", f"处理过程出错: {str(e)}")
        
        finally:
            # 重新启用按钮
            for widget in self.root.winfo_children():
                if isinstance(widget, ttk.Button):
                    widget.configure(state='normal')
    
    def log_message(self, message):
        """将消息添加到消息队列"""
        self.message_queue.put(message)
    
    def check_message_queue(self):
        """检查消息队列并更新日志"""
        try:
            while True:
                message = self.message_queue.get_nowait()
                self.log_text.insert(tk.END, message + "\n")
                self.log_text.see(tk.END)
        except queue.Empty:
            pass
        finally:
            # 每100ms检查一次消息队列
            self.root.after(100, self.check_message_queue)

def main():
    root = tk.Tk()
    app = MediaOrganizerGUI(root)
    root.mainloop()

if __name__ == "__main__":
    main() 